<?php
namespace common\repositories\myhtsq;

use common\entities\myhtsq\ContractEmailContactsEntity;
use common\repositories\BaseRepository;

class ContractEmailContactsRepository extends BaseRepository
{
    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = []) {
        parent::__construct($config);
    }

    /**
     * 获取用户需要抄送邮件的联系人
     * @param $buId 用户所在公司
     * @param $userCode 用户code
     * @return array 抄送联系人列表
     */
    public static function getCCContactsByBu($buId, $userCode)
    {
        $contactsEntity = new ContractEmailContactsEntity();
        $query = $contactsEntity::find();
        $query->where(['bu_id' => $buId])->orderBy(['level' => SORT_ASC]);

        $contacts = $query->asArray()->all();

        $level = 1;
        $copyTo = [];
        if (is_array($contacts)) {
            $copyTmp = [];
            foreach ($contacts as $key => $item) {
                if ($level != $item['level']) {
                    $copyTo = array_merge($copyTo, $copyTmp);
                    $copyTmp = [];
                }

                if ($userCode == $item['user_code']) {
                    $copyTmp = [];
                    break;
                }

                array_push($copyTmp, $item['user_code']);
            }
            $copyTo = array_merge($copyTo, $copyTmp);
        }

        $copyToEMail = [];
        foreach ($copyTo as $key => $item) {
            $userTmp = ErpUserRepository::getUserByCode($item);
            $copyToEMail[$userTmp['Email']] = $userTmp['UserName'];
        }

        return $copyToEMail;
    }

}